<template>
  <div>
    <div
      class="container"
      v-if="!showUnitadd && !showUnitdetail && !showcheckreport"
    >
      <div class="container-search">
        <!-- <div class="container-search-top"></div> -->
        <div class="container-search-bottom">
          <!-- 筛选条件 -->
          <div class="search">
            <div class="search-item">
              <el-input
                v-model="params.name"
                placeholder="请输入单位名称"
                clearable
                maxlength="25"
                class="search-input"
              />
            </div>
            <div class="search-item">
              <el-cascader
                v-model="params.region"
                placeholder="请选择行政区划"
                :options="options"
                filterable
                clearable
                :props="areaprops"
                @change="handlerregion"
              />
            </div>
            <div class="search-item">
              <el-select
                v-model="params.typeId"
                placeholder="请选择单位类型"
                clearable
                class="search-input"
              >
                <el-option
                  v-for="dict in unittypeList"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </div>
            <div class="search-item">
              <el-select
                v-model="params.levelId"
                placeholder="请选择单位级别"
                clearable
                class="search-input"
              >
                <el-option
                  v-for="dict in unitlevelList"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </div>
            <div class="search-item">
              <el-select
                v-model="params.industryId"
                placeholder="请选择所属行业"
                clearable
                class="search-input"
              >
                <el-option
                  v-for="dict in supervisorList"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </div>
            <div class="search-item">
              <el-button type="primary" @click="getunitList(true)"
                ><img src="@/assets/images/search.png" alt="" /> 搜索</el-button
              >
              <el-button color="#eff3ff" :dark="true" @click="reset"
                ><img src="@/assets/images/reset.png" alt="" />
                <span style="color: #6d98fd">重置 </span>
              </el-button>
              <el-button type="primary" @click="addunit"
                ><img src="@/assets/images/add.png" alt="" />新增</el-button
              >
            </div>
          </div>
        </div>
      </div>
      <div class="container-button">
        <!-- <el-button type="primary" @click="addunit"
          ><img src="@/assets/images/add.png" alt="" />新增</el-button
        > -->
        <el-select
          v-model="params.sortField"
          placeholder="请选择时间排序类型"
          clearable
          class="search-input"
          @change="handlersort"
        >
          <el-option
            v-for="dict in sortList"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </div>

      <div class="container-table">
        <!-- 表格筛选 -->
        <!-- <div class="sort">
          <div class="sort-title">排序类型：</div>
          <el-select
            v-model="params.sortField"
            placeholder="按时间排序"
            clearable
            class="search-input"
            @change="handlersort"
          >
            <el-option
              v-for="dict in sortList"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </div> -->
        <!-- 表格数据 -->
        <el-table
          v-loading="loading"
          :data="unitList"
          border
          height="62vh"
          :header-cell-style="{ 'text-align': 'center' }"
        >
          <el-table-column
            label="操作"
            :show-overflow-tooltip="true"
            :resizable="false"
          >
            <template #default="{ row }">
              <div class="table-operate">
                <span class="detail" @click="handleOperate('detail', row)"
                  >详情</span
                >
                <span class="edit" @click="handleOperate('edit', row)"
                  >编辑</span
                >
                <span
                  class="check"
                  @click="handleOperate('check', row)"
                  v-if="[1].includes(userStore.deptType)"
                  >检查</span
                >
                <span class="delete" @click="handleOperate('delete', row)"
                  >删除</span
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="单位名称"
            prop="name"
            width="200"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            label="行政区划"
            prop="areaName"
            width="200"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            label="单位类型"
            width="150"
            prop="institutionType"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            label="单位级别"
            width="150"
            prop="levelName"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            label="所属行业"
            prop="industryName"
            :show-overflow-tooltip="true"
            width="180"
          >
          </el-table-column>
          <el-table-column
            label="所属派出所"
            prop="policeStationName"
            :show-overflow-tooltip="true"
            width="150"
          >
          </el-table-column>
          <el-table-column
            label="责任人"
            prop="leader"
            :show-overflow-tooltip="true"
            width="180"
          >
          </el-table-column>
          <el-table-column
            label="最近检查时间"
            prop="lastCheckTime"
            :show-overflow-tooltip="true"
          >
            <template #default="{ row }">
              {{ row.lastCheckTime || "--" }}
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <pagination
          class="pagination"
          :total="total"
          v-model:page="params.pageNum"
          v-model:limit="params.pageSize"
          @pagination="getunitList"
        />
      </div>
    </div>
    <!-- 添加 -->
    <Card title="创建单位" v-if="showUnitadd">
      <template #content>
        <Unitadd
          v-if="showUnitadd"
          v-model:showUnitadd="showUnitadd"
          :unitlevelList="unitlevelList"
          :supervisorList="supervisorList"
          :unittypeList="unittypeList"
          @refreshList="reset"
          ref="Unitaddref"
        ></Unitadd>
      </template>
    </Card>

    <!-- 详情 -->
    <Unitdetail
      v-if="showUnitdetail"
      ref="Unitdetailref"
      v-model:showUnitdetail="showUnitdetail"
    ></Unitdetail>

    <!-- 检查上报 -->
    <Checkreport
      ref="checkreportref"
      v-if="showcheckreport"
      v-model:showcheckreport="showcheckreport"
      @refreshList="reset"
    ></Checkreport>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import Card from "@/components/Card";
import Unitadd from "./unitadd";
import Unitdetail from "./unitdetail";
import Checkreport from "../../task/checkreport";
import { getinstitutionlist, delinstitution } from "@/api/erp/unit";
import { getDictsApi, getAreaList } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
import useUserStore from "@/store/modules/user";

const userStore = useUserStore();

// 搜索参数
let params = ref({
  pageNum: 1,
  pageSize: 20,
  sortOrder: "DESC",
  region: [],
  provinceId: "",
  cityId: "",
  zoneId: "",
  streetId: "",
});
// 总数
const total = ref(0);

//行政区划数据
let options = ref([]);

// 表格加载效果
const loading = ref(false);

// 项目列表
const unitList = ref([{}]);

// 单位类型下拉
const unittypeList = ref([]);
// 单位级别下拉
const unitlevelList = ref([]);
// 行业主管下拉
const supervisorList = ref([]);
// 排序下拉
const sortList = ref([]);

// 添加弹窗的显隐
let showUnitadd = ref(false);
// 详情弹窗的显隐
let showUnitdetail = ref(false);
let showcheckreport = ref(false);

//详情组件的引用
const Unitdetailref = ref(null);
//添加编辑的引用
const Unitaddref = ref(null);
//检查上报的引用
const checkreportref = ref(null);

const areaprops = {
  lazy: true,
  checkStrictly: true,
  lazyLoad(node, resolve) {
    console.log("node", node);
    const { level } = node;
    let datas = [];
    setTimeout(() => {
      let code = 1;
      if (level != 0) {
        code = node.data.value;
      }
      getAreaList({ pid: code }).then((response) => {
        if (response.data && response.data.length) {
          datas = response.data.map((item, i) => ({
            value: item.value,
            label: item.label,
            leaf: level >= 3,
            // disabled: true, // 这里可以设置为 true 来禁用这个选项
          }));
        } else {
          datas = [];
        }
        resolve(datas);
      });
    }, 200);
  },
};

/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.value.pageNum;
  const pageSize = params.value.pageSize;
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  return truelndex;
}
/**
 * @description: 表格数据接口
 */
const getunitList = (flag = false) => {
  if (flag == true) {
    params.value.pageNum = 1;
    params.value.pageSize = 20;
  }
  loading.value = true;
  getinstitutionlist(
    { pageNum: params.value.pageNum, pageSize: params.value.pageSize },
    params.value
  ).then((res) => {
    unitList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  });
};

/**
 * @description: 重置
 */
const reset = () => {
  params.value = {
    pageNum: 1,
    pageSize: 20,
    sortOrder: "DESC",
    region: [],
    provinceId: "",
    cityId: "",
    zoneId: "",
    streetId: "",
  };
  getunitList();
};

/**
 * @description: 联级处理省市区操作
 * @param {String} type 类型
 */
const handlerregion = (value) => {
  if (value) {
    switch (value.length) {
      case 1:
        params.value.provinceId = value[0];
        break;
      case 2:
        params.value.provinceId = value[0];
        params.value.cityId = value[1];
        break;
      case 3:
        params.value.provinceId = value[0];
        params.value.cityId = value[1];
        params.value.zoneId = value[2];
        break;
      case 4:
        params.value.provinceId = value[0];
        params.value.cityId = value[1];
        params.value.zoneId = value[2];
        params.value.streetId = value[3];
        break;

      default:
        break;
    }
  } else {
    params.value.region = [];
    params.value.provinceId = null;
    params.value.cityId = null;
    params.value.zoneId = null;
    params.value.streetId = null;
  }
};
/**
 * @description: 表格数据接口
 */
const addunit = () => {
  showUnitadd.value = true;
};

/**
 * @description: 表格数据接口
 */
const handlersort = (value) => {
  getunitList();
};
/**
 * @description: 表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
const handleOperate = async (type, row) => {
  switch (type) {
    case "detail":
      showUnitdetail.value = true;
      nextTick(() => {
        Unitdetailref.value.handleDetailInfo(row);
      });
      break;
    case "edit":
      showUnitadd.value = true;
      nextTick(() => {
        Unitaddref.value.handleEdit(row);
      });
      break;

    case "check":
      showcheckreport.value = true;
      nextTick(() => {
        checkreportref.value.handleReport(row);
      });
      break;

    case "delete":
      ElMessageBox.confirm("此操作将删除该重点单位，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          const res = await delinstitution(row.institutionId);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getunitList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;

    default:
      break;
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  await getDictsApi("institution_type").then((res) => {
    //单位类型下拉
    if (res.code === 200) {
      unittypeList.value = res.data;
    }
  });
  await getDictsApi("institution_industry_type").then((res) => {
    //行业主管下拉
    if (res.code === 200) {
      supervisorList.value = res.data;
    }
  });
  await getDictsApi("fkwz_institution_level_type").then((res) => {
    //单位级别下拉
    if (res.code === 200) {
      unitlevelList.value = res.data;
    }
  });
  await getDictsApi("order_by_time_type").then((res) => {
    //单位级别下拉
    if (res.code === 200) {
      sortList.value = res.data;
    }
  });
  // await getAreaList({ pid: 1 }).then((res) => {
  //   options.value = res.data;
  // });
}

onMounted(() => {
  getunitList();
  getDicts();
});
</script>

<style scoped lang="scss">
.container {
  position: relative;
  .container-search {
    margin-bottom: 12px;
    .container-search-bottom {
      background-color: #ffffff;
      border-radius: 10px;
      padding: 15px 15px 15px 15px;
    }
  }

  .container-button {
    position: absolute;
    top: 15px;
    right: 15px;
    img {
      margin-right: 6px;
      margin-top: 2px;
    }
  }
  .container-table {
    background-color: #ffffff;
    border-radius: 10px;
    padding: 15px 15px 15px 15px;
    .sort {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      margin-bottom: 15px;
      .sort-title {
        font-size: 14px;
      }
    }
  }
}
</style>
